package com.ruoyi.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.ruoyi.common.core.domain.AjaxResult.CODE_TAG;
import static com.ruoyi.common.core.domain.AjaxResult.MSG_TAG;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");
        if (body instanceof Map) {
            if (((Map) body).containsKey("code") && ((Map) body).containsKey("data")) {
                return body;
            }
        }else if(body instanceof AjaxResult || body instanceof TableDataInfo){
            return body;
        } else if (body instanceof Page) {
            return responsePageOk((Page) body);
        }
        return responseOk(body);
    }

    private Object responseOk(Object obj) {
        Map<String, Object> map = new ConcurrentHashMap<String, Object>();
        map.put(CODE_TAG, HttpStatus.SUCCESS);
        map.put(MSG_TAG, "执行成功");
        if (obj != null) {
            map.put("data", obj);
        }
        if (obj instanceof String) {
            return JSON.toJSONString(map);
        }
        return map;
    }

    private Object responsePageOk(Page page) {
        Map<String, Object> map = new ConcurrentHashMap<String, Object>();
        map.put(CODE_TAG, HttpStatus.SUCCESS);
        map.put(MSG_TAG, "执行成功");
        map.put("data", page.getRecords());
        map.put("total", page.getTotal());
        map.put("data_count", page.getTotal());
        return map;
    }
}
